<template>
   <el-menu
    :default-active="activeIndex2"
    class="el-menu-demo"
    mode="horizontal"
    background-color="#545c64"
    text-color="#fff"
    active-text-color="#ffd04b"
    @select="handleSelect"
  >
    <el-menu-item index="/list">首页</el-menu-item>
    <el-menu-item index="/add">添加联系人</el-menu-item>
    <el-sub-menu index="3">
      <template #title>我的</template>
      <el-menu-item index="/login">登录</el-menu-item>
      <el-menu-item index="3-2">注销</el-menu-item>
      <el-menu-item index="3-3">修改资料</el-menu-item>
      <el-sub-menu index="3-4">
          <template #title>统计</template>
          <el-menu-item index="/report" v-if="checkRole('/report')">柱形图</el-menu-item>
          <el-menu-item index="/report02" v-if="checkRole('/report02')">饼图</el-menu-item>
      </el-sub-menu>
    </el-sub-menu>
  </el-menu>
</template>

<script setup>
import { ref,defineExpose } from 'vue'
import {useRouter} from 'vue-router'
import {userStore} from '../store/UserStore.js'

const activeIndex2 = ref('1')
const router=useRouter();
const store=userStore();

const handleSelect =function(key, keyPath) {
  console.log(this)
  console.log(key, keyPath)
  router.push(key);
  // switch (key) {
  //   case '3-1':
  //     router.push("/login");
  //     break;
  //   case '1':
  //     router.push("/list")
  //     break;
  //   case '2':
  //     router.push("/add")
  //     break;
  //   case '3-4-1':
  //     router.push("/report")
  //     break;
  //   case '3-4-2':
  //     router.push("/report02")
  //     break;
  //   case '6':
     
  // }
}

// 获取所有路由配置（包括嵌套路由）
function getAllRoutes(routeList) {
  const rolePaths = []

  routeList.forEach(route => {
    if (route.meta && route.meta.roles) {
      rolePaths[route.path]=route.meta.roles
    }
    // 递归处理嵌套路由
    if (route.children && route.children.length) {
      let rr= getAllRoutes(route.children)
      for(let k in rr)
        rolePaths[k]=rr[k]
    }
  })
  return rolePaths
}

// 使用示例
const allRoutes = getAllRoutes(router.options.routes)
console.log(allRoutes)
function checkRole(path) {
  if(!allRoutes[path])
    return true;
  if(store.user==null)
    return false;
  return allRoutes[path].includes(store.user.role)
}
  
// 暴露方法供模板使用
// defineExpose({
//   checkRole
// })
</script>
